<template>
	<div class="finance-container">
		<div class="dataScreen" ref="dataScreenRef">
			<ScreenHeader :titleImg="postTitleImg"></ScreenHeader>
			<div class="property-main">
				<!-- 左边 -->
				<div class="dataScreen-lf">
					<div class="lf-top">
						<ul>
							<li
								class="lf-top-item"
								v-for="(item, idx) in outpatientFinancials"
								:key="idx"
							>
								<div class="lf-top-icon"></div>
								<span class="lf-top-text">{{ item.name }}</span>
								<span class="lf-top-unit">
									<span class="lf-top-money">{{
										changeNumToWan(item.value)
									}}</span>
									万元
								</span>
							</li>
						</ul>
					</div>
					<div class="lf-bottom">
						<div class="statistics">
							<ItemTitle2 :itemTitleImg="postItemTitleImgObj['门诊营收统计']">
							</ItemTitle2>
							<div class="revenueStatistics" ref="revenueStatistics"></div>
						</div>

						<div class="statistics">
							<ItemTitle2 :itemTitleImg="postItemTitleImgObj['门诊支出统计']">
							</ItemTitle2>
							<div
								class="expendituresStatistics"
								ref="expendituresStatistics"
							></div>
						</div>
					</div>
				</div>
				<!-- 中间 -->
				<div class="dataScreen-ct">
					<div class="ct-top">
						<timeRange @timeSelect="timeChange" />
						<div class="ct-top-incomeAndExpenses m-t10">
							<div
								class="incomeAndExpenses"
								v-for="(item, index) in incomeAndExpensesData"
								:key="index"
							>
								<div>
									<div class="title">
										<img :src="incomeAndExpensesImgs[index]" :alt="item.name" />
									</div>
									<div class="money">
										{{ item.value }}
										<span class="unit">万元</span>
									</div>
								</div>
							</div>
						</div>
						<div class="ct-top-passengerFlow">
							<div
								class="passengerFlow"
								v-for="(item, index) in passengerFlowData"
								:key="index"
							>
								<div class="flex">
									<div class="title">
										<img :src="passengerFlowImgs[index]" :alt="item.name" />
									</div>
									<div
										class="rate"
										:style="{
											color: item.isAdd === 1 ? '#10FF0E' : '#F50000',
										}"
									>
										<img
											v-if="item.isAdd === 0"
											:src="downIcon"
											alt="同比下降"
										/>
										<img v-else :src="upIcon" alt="同比上升" />
										{{ item.rate }}
									</div>
								</div>
								<div class="people-number">
									<span>{{ item.value }}</span>
									<img :src="peopleUnit" alt="人" />
								</div>
							</div>
						</div>
					</div>
					<div class="ct-center">
						<ItemTitle2 :itemTitleImg="postItemTitleImgObj['各院框架情况']">
						</ItemTitle2>
						<div class="flex" style="height: calc(100% - 90px)">
							<div class="ct-left">
								<div class="chartsBase"></div>
								<div class="charts3D" ref="leftPieCharts"></div>
							</div>
							<div class="ct-right">
								<!--                <div class="chartsBase"></div>-->
								<div class="charts3D" ref="rightPieCharts"></div>
							</div>
						</div>
					</div>
					<div class="ct-bottom">
						<!--            <CenterMap height="100%" idName="CenterMap" ref="centerMap"/>-->
						<CenterMap ref="centerMap" />
					</div>
				</div>
				<!-- 右边 -->
				<div class="dataScreen-rg">
					<div class="rg-top">
						<ItemTitle2 :itemTitleImg="postItemTitleImgObj['实验室检验情况']">
						</ItemTitle2>
						<div class="laboratoryInspect" ref="laboratoryInspect"></div>
					</div>
					<div class="rg-bottom">
						<ItemTitle2 :itemTitleImg="postItemTitleImgObj['实验室营收统计']">
						</ItemTitle2>
						<div style="position: relative; flex: 1">
							<div class="legends">
								<div class="legend" style="margin-right: 40px">
									<div class="legendIcon"></div>
									<span class="legendText">支出</span>
								</div>
								<div class="legend">
									<div class="legendIcon1"></div>
									<span class="legendText">收入</span>
								</div>
							</div>
							<div
								class="laboratoryRevenueStatistics"
								ref="laboratoryRevenueStatistics"
							></div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import ScreenHeader from "../components/ScreenHeader";
import { getScale, changeNumToWan } from "../utils/handelScreen";
import ItemTitle2 from "../finance/components/ItemTitle";
// import CenterMap from '@/components/BaseMap'
import CenterMap from "./components/map";
import { initRevenueCharts } from "./utils/utils";
import { bindListen, getPie3D } from "./utils/pie3D";
import { initBarCahrts, initBidirectionBar } from "./utils/bar";
import * as echarts from "echarts";
import "echarts-gl";
import {
	getMedicalDistributionList,
	getMedicalLaboratoryList,
	getMedicalLaboratoryRevenueList,
	getMedicalOutpatientExpenditureList,
	getMedicalOutpatientList,
	getMedicalOutpatientPersonnelList,
	getMedicalOutpatientRevenueList,
	getMedicalOutpatientTrafficList,
	getMedicalRevenueExpenditureList,
} from "@/api/dashboard/medical";
import { generateHexColor } from "@/utils/commonFn";
import timeRange from "../components/timeRange.vue";

const downIcon = require("@/assets/screenImg/commonImg/down.png");
const upIcon = require("@/assets/screenImg/commonImg/up.png");
const peopleUnit = require("@/assets/screenImg/medicalImg/people-unit.png");
const postTitleImg = require("@/assets/screenImg/medicalImg/title.png");
const postItemTitleImgObj = reactive({
	门诊营收统计: require("@/assets/screenImg/medicalImg/title1.png"),
	门诊支出统计: require("@/assets/screenImg/medicalImg/title2.png"),
	各院框架情况: require("@/assets/screenImg/medicalImg/title5.png"),
	实验室检验情况: require("@/assets/screenImg/medicalImg/title3.png"),
	实验室营收统计: require("@/assets/screenImg/medicalImg/title4.png"),
});
const dataScreenRef = ref(null);
const screenResize = () => {
	if (dataScreenRef.value) {
		dataScreenRef.value.style.transform = `scale(${getScale()}) translate(-50%, -50%)`;
	}
};

// region 门诊收支情况
const outpatientFinancials = ref([]);
const getOutpatientFinancials = async () => {
	const { httpStatusCode, data } = await getMedicalOutpatientList();
	if (httpStatusCode === 200) {
		data.records.forEach((item) => {
			const newObj1 = {
				name: item.outpatient_serv_name + "营收情况",
				value: item.outpatient_income,
				ts: item.ts,
				isIncome: true,
			};

			const newObj2 = {
				name: item.outpatient_serv_name + "支出情况",
				value: item.outpatient_expenses,
				ts: item.ts,
				isIncome: false,
			};
			outpatientFinancials.value.push(newObj1, newObj2);
		});
	}
};
// endregion

// region 门诊营收统计
const revenueStatistics = ref(null);
const revenueStatisticsCahrts = ref(null);
const revenueStatisticsData = ref([]);
const getRevenueStatistics = async () => {
	const { data, httpStatusCode } = await getMedicalOutpatientRevenueList();
	if (httpStatusCode === 200) {
		revenueStatisticsData.value = data.records.map((item) => ({
			name: item.expense_type,
			value: changeNumToWan(item.amount),
			proportion:
				item.proportion <= 1
					? (item.proportion * 100).toFixed(2)
					: item.proportion,
		}));
		// 营收饼状图
		revenueStatisticsCahrts.value = initRevenueCharts(
			revenueStatistics.value,
			revenueStatisticsData.value
		);
	}
};
// endregion

// region 门诊支出统计
const expendituresStatisticsCahrts = ref(null);
const expendituresStatistics = ref(null);
const expendituresStatisticsData = ref([]);
const getExpendituresStatisticsData = async () => {
	const { data, httpStatusCode } = await getMedicalOutpatientExpenditureList();
	if (httpStatusCode === 200) {
		expendituresStatisticsData.value = data.records.map((item) => ({
			name: item.expense_type,
			value: changeNumToWan(item.amount),
			proportion:
				item.proportion <= 1
					? (item.proportion * 100).toFixed(2)
					: item.proportion,
		}));

		//  支出饼状图
		expendituresStatisticsCahrts.value = initRevenueCharts(
			expendituresStatistics.value,
			expendituresStatisticsData.value
		);
	}
};
// endregion

// region 医疗收支统计
// 收入、支出、利润的icon
const incomeAndExpensesImgs = ref([
	require("@/assets/screenImg/medicalImg/revenue.png"),
	require("@/assets/screenImg/medicalImg/expenditures.png"),
	require("@/assets/screenImg/medicalImg/profit.png"),
]);
// 收入、支出、利润的数据
const incomeAndExpensesData = ref([
	{
		name: "总收入",
		value: 0,
	},
	{
		name: "总支出",
		value: 0,
	},
	{
		name: "总利润",
		value: 0,
	},
]);
const getIncomeAndExpensesData = async () => {
	const { data, httpStatusCode } = await getMedicalRevenueExpenditureList();
	if (httpStatusCode === 200) {
		incomeAndExpensesData.value[0].value = changeNumToWan(
			data.records[0].total_medical_income
		);
		incomeAndExpensesData.value[1].value = changeNumToWan(
			data.records[0].total_medical_expenses
		);
		incomeAndExpensesData.value[2].value = changeNumToWan(
			data.records[0].total_medical_profit
		);
	}
};
// endregion

// region 客流量数据
// 客流量的icon
const passengerFlowImgs = ref([
	require("@/assets/screenImg/medicalImg/passengerFlow1.png"),
	require("@/assets/screenImg/medicalImg/passengerFlow2.png"),
]);
// 客流量数据
const passengerFlowData = ref([
	{
		name: "门诊客流量",
		isAdd: "",
		rate: "",
		value: "",
	},
	{
		name: "新增客流量",
		isAdd: "",
		rate: "",
		value: "",
	},
]);
const getPassengerFlowData = async () => {
	const { data, httpStatusCode } = await getMedicalOutpatientTrafficList();
	if (httpStatusCode === 200) {
		const result = data.records[0];
		passengerFlowData.value[0].value = result.traffic_volume;
		passengerFlowData.value[0].isAdd = result.growth >= 0 ? 1 : 0;
		passengerFlowData.value[0].rate =
			(Math.abs(result.growth) * 100).toFixed(0) + "%";

		passengerFlowData.value[1].value = result.new_traffic_volume;
		passengerFlowData.value[1].isAdd = result.new_growth >= 0 ? 1 : 0;
		passengerFlowData.value[1].rate =
			(Math.abs(result.new_growth) * 100).toFixed(0) + "%";
	}
};
// endregion

// region 各院框架情况饼图-门诊人员框架情况
const leftPieCharts = ref(null);
const rightPieCharts = ref(null);

const pieChartsRefList = ref([leftPieCharts, rightPieCharts]);
const pieColors = [
	"#05cff7",
	"#1978e5",
	"#eab966",
	"#60b45e",
	"#becdd0",
	"#ea6666",
	"#ff3bba",
	"#b166ea",
];
const getMedicalOutpatientPersonnel = async () => {
	const { data, httpStatusCode } = await getMedicalOutpatientPersonnelList();
	if (httpStatusCode === 200) {
		const obj = {};
		data.records.forEach((item) => {
			const { outpatient_serv_name } = item;
			if (!obj[outpatient_serv_name]) {
				obj[outpatient_serv_name] = {
					pieName: outpatient_serv_name,
					children: [
						{
							department_name: item.department_name,
							department_staff: item.department_staff,
						},
					],
				};
			} else {
				if (outpatient_serv_name === obj[outpatient_serv_name].pieName) {
					obj[outpatient_serv_name].children.push({
						department_name: item.department_name,
						department_staff: item.department_staff,
					});
				}
			}
		});

		const instanceVal = Object.values(obj);

		instanceVal.forEach((item, idx) => {
			const optionData = item.children.map((subItem, index) => ({
				name: subItem.department_name,
				value: subItem.department_staff,
				itemStyle: {
					color: pieColors[index],
				},
				// color: generateHexColor()
			}));
			console.log(optionData);
			initPie(pieChartsRefList.value[idx].value, optionData, item.pieName);
		});
	}
};
const initPie = (dom, data, title) => {
	//构建3d饼状图
	let myChart = echarts.init(dom);
	// 传入数据生成 option ; getPie3D(数据，透明的空心占比（调节中间空心范围的0就是普通饼1就很镂空）)
	let option = getPie3D(data, 0.8, title);
	//将配置项设置进去
	myChart.setOption(option);
	//鼠标移动上去特效效果
	bindListen(myChart, option);
	return myChart;
};
// endregion

// region 实验室检验情况
const laboratoryInspect = ref(null);
const laboratoryInspectData = ref({
	XData: [],
	barData: [],
	lineData: [],
});
const getLaboratoryInspectData = async () => {
	const { data, httpStatusCode } = await getMedicalLaboratoryList();
	if (httpStatusCode === 200) {
		const result = data.records;
		laboratoryInspectData.value.XData = result.map(
			(item) => item.examination_type
		);
		laboratoryInspectData.value.barData = result.map(
			(item) => item.examination_num
		);
		laboratoryInspectData.value.lineData = result.map(
			(item) => item.examination_people
		);
	}

	// 实验室检验情况图表
	initBarCahrts(laboratoryInspect.value, laboratoryInspectData.value);
};
// endregion

// region 实验室营收统计图表
const laboratoryRevenueStatistics = ref(null);
const laboratoryRevenueStatisticsData = ref({
	XData: [],
	income: [],
	disburse: [],
});
const getMedicalLaboratoryRevenue = async () => {
	const params = {
		year: new Date().getFullYear(),
	};
	const { data, httpStatusCode } = await getMedicalLaboratoryRevenueList(
		params
	);
	if (httpStatusCode === 200) {
		const result = data.records;
		laboratoryRevenueStatisticsData.value.XData = result.map(
			(item) => item.month
		);
		laboratoryRevenueStatisticsData.value.income = result.map((item) =>
			changeNumToWan(item.laboratory_income)
		);
		laboratoryRevenueStatisticsData.value.disburse = result.map((item) =>
			changeNumToWan(item.laboratory_expenses)
		);
	}
	// 实验室营收统计图表
	initBidirectionBar(
		laboratoryRevenueStatistics.value,
		laboratoryRevenueStatisticsData.value
	);
};
// endregion

// region 获取中间地图的数据
const mapData = ref();
const centerMap = ref();
const getMapDataList = async () => {
	const { data, httpStatusCode } = await getMedicalDistributionList();
	if (httpStatusCode === 200) {
		mapData.value = data.records;
		centerMap.value?.createMarker(mapData.value);
	}
};
// endregion

let timeChange = (time) => {
	console.log(time);
};

const getPageData = () => {
	getOutpatientFinancials();
	getRevenueStatistics();
	getExpendituresStatisticsData();
	getIncomeAndExpensesData();
	getPassengerFlowData();
	getMedicalOutpatientPersonnel();
	getLaboratoryInspectData();
	getMedicalLaboratoryRevenue();
	getMapDataList();
};
onMounted(() => {
	if (dataScreenRef.value) {
		dataScreenRef.value.style.transform = `scale(${getScale()}) translate(-50%, -50%)`;
		dataScreenRef.value.style.width = `1920px`;
		dataScreenRef.value.style.height = `1080px`;
		window.addEventListener("resize", () => {
			screenResize();
			revenueStatisticsCahrts.value.resize();
			expendituresStatisticsCahrts.value.resize();
		});
	}
	getPageData();
});
onBeforeUnmount(() => {
	window.removeEventListener("resize", screenResize);
});
</script>
<style lang="scss" scoped>
@import "./medical.scss";
</style>
